package com.qzdsoft.erpcloud.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.erpcloud.service.sys.SysTableAuthService;
import com.qzdsoft.erpcloud.service.sys.TablePermission;
import com.qzdsoft.utils.StringUtil;

@Component
public class TablePermissionInterceptor implements HandlerInterceptor
{
 private static final Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
    
    @Autowired
    private SysTableAuthService sysTableAuthService;
    
    @Value("${permission.validate}")
    private Boolean permissionValidate;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception
    {
        
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse arg1, Object handler, ModelAndView mv) throws Exception
    {
      //如果配置文件配置不需要权限验证 直接返回true （开发时可以配置为false）
        if(!permissionValidate) {
            return;
        }
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
           TablePermission permission = handlerMethod.getMethod().getAnnotation(TablePermission.class);
           if (permission != null && !StringUtil.isEmpty(permission.id())) //不需要验证权限
           {
               LoginUser user = (LoginUser)request.getAttribute("user");
               List<String> tableFileds = sysTableAuthService.queryAuthrizedTableFields(user.getId(), permission.id());
               mv.addObject("fields", tableFileds);
           }
           
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        return true;
    }
    
}
